/**
 * 238. 除自身以外数组的乘积
 * https://leetcode-cn.com/problems/product-of-array-except-self/
 */
const { displayBaseArray } = require('../../libs/public');

/**
 * @param {number[]} nums
 * @return {number[]}
 */
function productExceptSelf(nums) {
  const result = new Array(nums.length);
  let pre = 1;
  for (let i = 0; i < nums.length; i += 1) {
    result[i] = pre;
    pre *= nums[i];
  }
  pre = 1;
  for (let i = nums.length - 1; i >= 0; i -= 1) {
    result[i] *= pre;
    pre *= nums[i];
  }
  return result;
}

console.log(displayBaseArray(productExceptSelf([1, 2, 3, 4])) === '[24,12,8,6]');
console.log(displayBaseArray(productExceptSelf([-1, 1, 0, -3, 3])) === '[0,0,9,0,0]');
